/**
 * Filename: NativeStickyGridAdapter.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/10 0:37
 */
package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.fragment.LocalAlbumImportFragment;
import com.github.postsanf.yinian.nativestick.StickyGridHeadersGridView;
import com.github.postsanf.yinian.nativestick.StickyGridHeadersSimpleAdapter;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.SpUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class LocalStickyImportGridAdapter extends BaseAdapter implements
        StickyGridHeadersSimpleAdapter {

    private boolean isSelectStatus;     // 是否在选择状态
    private List<YNNativeImage> hasHeaderIdList;
    private LayoutInflater mInflater;
    private ImageLoader imageLoader;
    private Context mContext;
    private LocalAlbumImportFragment fragment;
    private Resources mResource;
    private List<String> list = new ArrayList<>();
    private Map<String, Boolean> click = new HashMap<>();
    private List<String> localUrl = new ArrayList<>();
    private StickyGridHeadersGridView mNative_grid_view;
    private Map<String,ImageView> headView=new HashMap<>();
    public void setResource(Resources mResource) {
        this.mResource = mResource;
    }

    public LocalStickyImportGridAdapter(Context mContext, List<YNNativeImage> hasHeaderIdList, boolean isSelectStatus, StickyGridHeadersGridView mNative_grid_view) {
        mInflater = LayoutInflater.from(mContext);
        this.mContext = mContext;
        this.mNative_grid_view=mNative_grid_view;
        this.hasHeaderIdList = hasHeaderIdList;
        this.isSelectStatus = isSelectStatus;

        imageLoader = ImageLoader.getInstance();
        if (YNSingleton.getInstance().getNativePhoto().size() == 0 || YNSingleton.getInstance().getNativePhoto() != hasHeaderIdList) {
            YNSingleton.getInstance().setNativePhoto(hasHeaderIdList);
        }
    }

    public void setSelectStatus(boolean isSelectStatus) {
        this.isSelectStatus = isSelectStatus;
    }

    @Override
    public int getCount() {
        return hasHeaderIdList.size();
    }

    @Override
    public Object getItem(int position) {
        return hasHeaderIdList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder mViewHolder;
        if (convertView == null) {
            mViewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.yn_item_local_image, parent, false);
            mViewHolder.mImageView = (SimpleDraweeView) convertView.findViewById(R.id.native_item_image);
            mViewHolder.mNative_item_select = (ImageView) convertView.findViewById(R.id.native_item_select);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }

        final String path = hasHeaderIdList.get(position).getPath();
        mViewHolder.mImageView.setTag(path);

        mViewHolder.mImageView.setImageResource(R.drawable.pic_null);

        if (mResource != null) {
            mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("picture_unselected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
        } else {
            mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_import_unselected);
        }

        Uri uri = Uri.parse("file://" + path);
        ImageOptHelper.showFrescoNative(uri, mViewHolder.mImageView, mContext);

        // 设置图片宽高
        final int screenWidth = DisplayUtils.getScreenWidthPixels((Activity) mContext);
        int horizontalSpacing = DisplayUtils.dp2px(mContext, 2);
        int itemWidth = (screenWidth - 2 * horizontalSpacing) / 3;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(itemWidth, itemWidth);
        mViewHolder.mImageView.setLayoutParams(params);

        mViewHolder.mNative_item_select.setVisibility(View.VISIBLE);
        mViewHolder.mImageView.setColorFilter(null);
        // 图片选择事件
        mViewHolder.mImageView.setOnClickListener(new View.OnClickListener() {
            //选择，则将图片变暗，反之则反之
            @Override
            public void onClick(View v) {
                // 已经选择过该图片
                if (SelectedImg.mSelectedImage.contains(path)) {
                    SelectedImg.mSelectedImage.remove(path);
                    List<String> strings = SelectedImg.dateUrl.get(getTime(path));
                    strings.remove(path);
                    SelectedImg.dateUrl.put(getTime(path), strings);

                    if (mResource != null) {
                        mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("picture_unselected", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                    } else {
                        mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_import_unselected);
                    }
                    mViewHolder.mImageView.setColorFilter(null);
                    ScaleAnimation scaleAnimation = new ScaleAnimation(0.9f, 1.0f, 0.9f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setFillAfter(true);
                    mViewHolder.mImageView.setAnimation(scaleAnimation);
                    scaleAnimation.startNow();

                    //取消全选
                    click.put(hasHeaderIdList.get(position).getTime(), false);
                    if (headView.get(hasHeaderIdList.get(position).getTime())!=null){
                        headView.get(hasHeaderIdList.get(position).getTime()).setImageResource(R.drawable.all_unselected);
                    }
                    headView.put(hasHeaderIdList.get(position).getTime(),null);
                } else
                // 未选择该图片
                {
                    SelectedImg.mSelectedImage.add(path);
                    if (SelectedImg.dateUrl.containsKey(getTime(path))){
                        List<String> strings = SelectedImg.dateUrl.get(getTime(path));
                        strings.add(path);
                        SelectedImg.dateUrl.put(getTime(path), strings);
                    }else{
                        localUrl.add(path);
                        SelectedImg.dateUrl.put(getTime(path),localUrl);
                    }
                    if (mResource != null) {
                        mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("pictures_selected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                    } else {
                        mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_import_selected);
                    }
                    mViewHolder.mImageView.setColorFilter(Color.parseColor("#33000000"));
                    ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setFillAfter(true);
                    mViewHolder.mImageView.setAnimation(scaleAnimation);
                    scaleAnimation.startNow();
                }
            }
        });

        // 响应选择效果
        if (SelectedImg.mSelectedImage.contains(path)) {
            if (mResource != null) {
                mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("pictures_selected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
            } else {
                mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_import_selected);
            }
            mViewHolder.mImageView.setColorFilter(Color.parseColor("#33000000"));
            ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            scaleAnimation.setFillAfter(true);
            mViewHolder.mImageView.setAnimation(scaleAnimation);
            scaleAnimation.startNow();
        } else {
            if (mResource != null) {
                mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("pictures_selected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
            } else {
                mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_import_unselected);
            }
            mViewHolder.mImageView.setColorFilter(null);
            ScaleAnimation scaleAnimation = new ScaleAnimation(0.9f, 1.0f, 0.9f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            scaleAnimation.setFillAfter(true);
            mViewHolder.mImageView.setAnimation(scaleAnimation);
            scaleAnimation.startNow();
        }

//        // 点击图片大图查看
//        mViewHolder.mImageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(mContext, NativePreviewActivity.class);
//                intent.putExtra(CommonConstants.YNDATAS, position);
//                mContext.startActivity(intent);
//            }
//        });
        return convertView;
    }

    @Override
    public View getHeaderView(final int position, View convertView, ViewGroup parent) {
        final HeaderViewHolder mHeaderHolder;
        if (convertView == null) {
            mHeaderHolder = new HeaderViewHolder();
            convertView = mInflater.inflate(R.layout.yn_item_local_image_header, parent, false);
            mHeaderHolder.mTextView = (TextView) convertView.findViewById(R.id.native_header_time);
            mHeaderHolder.mimageButton = ((ImageView) convertView.findViewById(R.id.all_pic_select));
            convertView.setTag(mHeaderHolder);
        } else {
            mHeaderHolder = (HeaderViewHolder) convertView.getTag();
        }

        mHeaderHolder.mTextView.setText(hasHeaderIdList.get(position).getTime());
        //该位置是被点击全选还是取消全选还是没有被点击过
        if (!click.containsKey(mHeaderHolder.mTextView.getText().toString().trim()) || !click.get(mHeaderHolder.mTextView.getText().toString().trim())){
            mHeaderHolder.mimageButton.setImageResource(R.drawable.all_unselected);
        }else{
            mHeaderHolder.mimageButton.setImageResource(R.drawable.all_selected);
        }
        mHeaderHolder.mimageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!click.containsKey(mHeaderHolder.mTextView.getText().toString().trim()) || !click.get(mHeaderHolder.mTextView.getText().toString().trim())) {
                    for (int i = 0; i < hasHeaderIdList.size(); i++) {
                        if (TextUtils.equals(mHeaderHolder.mTextView.getText().toString().trim(), hasHeaderIdList.get(i).getTime())&&!SelectedImg.mSelectedImage.contains(hasHeaderIdList.get(i).getTime())) {
                            String path = hasHeaderIdList.get(i).getPath();
                            SelectedImg.mSelectedImage.add(path);
                            localUrl.add(path);
                        }
                    }
                    click.put(mHeaderHolder.mTextView.getText().toString().trim(), true);
                    headView.put(mHeaderHolder.mTextView.getText().toString().trim(),mHeaderHolder.mimageButton);
                    SelectedImg.dateUrl.put(mHeaderHolder.mTextView.getText().toString().trim(), localUrl);
                    notifyDataSetChanged();
                    mHeaderHolder.mimageButton.setImageResource(R.drawable.all_selected);
                } else {
                    list.clear();
                    for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                        list.add(SelectedImg.mSelectedImage.get(i));
                    }
                    ListIterator<String> it = list.listIterator();
                    while (it.hasNext()) {
                        String next = it.next();
                        if (TextUtils.equals(mHeaderHolder.mTextView.getText().toString().trim(), getTime(next))) {
                            SelectedImg.mSelectedImage.remove(next);
                            localUrl.remove(next);
                        }
                    }
                    click.put(mHeaderHolder.mTextView.getText().toString().trim(), false);
                    headView.put(mHeaderHolder.mTextView.getText().toString().trim(),null);
                    SelectedImg.dateUrl.put(mHeaderHolder.mTextView.getText().toString().trim(), localUrl);
                    notifyDataSetChanged();
                    mHeaderHolder.mimageButton.setImageResource(R.drawable.all_unselected);
                }
            }
        });
        return convertView;
    }

    private String getTime(String path) {
        File file = new File(path);
        long imgTime = file.lastModified();
        Date currentTime = new Date(imgTime);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    //  获取HeaderId,HeaderId不同则New一个
    @Override
    public long getHeaderId(int position) {
        return hasHeaderIdList.get(position).getSection();
    }

    public static class ViewHolder {
        public SimpleDraweeView mImageView;
        public ImageView mNative_item_select;
    }

    public static class HeaderViewHolder {
        public TextView mTextView;
        public ImageView mimageButton;
    }
}